<template>
  <div class="discover-container">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header class="discover-header">
        <div class="header-content">
          <!-- 左侧返回首页 -->
          <div class="back-home" @click="$router.push('/')">
            <el-icon style="font-size: 24px; margin-top: 5px"
              ><ArrowLeft
            /></el-icon>
            <span style="font-size: 24px">回到首页</span>
          </div>

          <!-- 中间搜索框 -->
          <div class="search-container">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索音乐、歌手、专辑"
              class="search-input"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="danger" class="search-btn" @click="handleSearch">
              搜索
            </el-button>
          </div>

          <!-- 右侧用户信息 -->
          <div class="user-info">
            <div class="login-register" v-if="!ifLogin">
              <span @click="dialogFormVisible = true" style="font-size: 24px"
                >登录</span
              >
              <span @click="goToRegister" style="font-size: 24px">注册</span>
            </div>

            <el-dropdown v-else>
              <div class="user-info-content">
                <img
                  src="../images/RecommendList1.png"
                  alt="用户头像"
                  class="user-avatar"
                />
                <span class="user-name">{{ userInfo.userInfoname }}</span>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goUserInfo"
                    >个人中心</el-dropdown-item
                  >
                  <el-dropdown-item @click="handleLogout"
                    >退出登录</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>

      <!-- 登录对话框 -->
      <el-dialog v-model="dialogFormVisible" title="登录" width="500">
        <el-form :model="form">
          <el-form-item label="账号" :label-width="formLabelWidth">
            <el-input v-model="form.username" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth">
            <el-input
              v-model="form.password"
              type="password"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="(dialogFormVisible = false), confirmLogin()"
            >
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 音乐列表 -->
      <el-main class="music-list-container">
        <div v-if="isLoading" class="loading-container">
          <el-icon class="is-loading" color="#ff4d4f" :size="40">
            <Loading />
          </el-icon>
        </div>

        <div v-else-if="errorMessage" class="error-container">
          <el-icon color="#ff4d4f" :size="40">
            <Warning />
          </el-icon>
          <p>{{ errorMessage }}</p>
        </div>

        <div v-else class="music-table">
          <div class="search-results" v-if="searchKeyword">
            <div class="result-title">搜索结果: {{ searchKeyword }}</div>
            <div class="result-count">
              {{ filteredMusicList.length }} 个结果
            </div>
          </div>
          <div class="table-header">
            <span class="title">歌曲名称</span>
            <span class="artist">歌手</span>
            <span class="action">操作</span>
          </div>
          <div class="table-body">
            <div
              v-for="music in currentPageData"
              :key="music.id"
              class="table-row"
              @click="goMusicDetail(music)"
            >
              <span class="title">{{ music.songtitle }}</span>
              <span class="artist">{{ music.songauthor }}</span>
              <el-icon
                class="like-icon"
                :style="{ color: music.isLiked ? '#ff4d4f' : '#666' }"
                @click.stop="toggleLike(music)"
              >
                <Star />
              </el-icon>
            </div>
          </div>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :background="true"
              layout="prev, pager, next"
              :total="filteredMusicList.length"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, computed, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  ArrowLeft,
  Search,
  Loading,
  Warning,
  VideoPlay,
  Star,
} from "@element-plus/icons-vue";

const router = useRouter();
const route = useRoute();

// 搜索关键词
const searchKeyword = ref("");

// 登录相关状态
const ifLogin = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = ref("120px");
const form = reactive({
  username: "",
  password: "",
});
const userInfo = reactive({
  userID: "",
  userInfoname: "",
  userToken: "",
});

// 音乐数据
const mockData = ref([]);
const musicList = ref([]);
const isLoading = ref(true);
const errorMessage = ref("");
const searchResults = ref([]);
const isSearching = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(15);

// 检查登录状态
const checkLoginStatus = () => {
  const userID = localStorage.getItem("userID");
  const userToken = localStorage.getItem("userToken");
  const userInfoname = localStorage.getItem("userInfoname");

  if (userID && userToken) {
    ifLogin.value = true;
    userInfo.userID = userID;
    userInfo.userInfoname = userInfoname;
    userInfo.userToken = userToken;
  }
};

// 登录确认
const confirmLogin = async () => {
  try {
    const response = await axios.post("http://localhost:3001/api/login", {
      username: form.username,
      password: form.password,
    });

    if (response.data.user) {
      ElMessage.success("登录成功");
      // 保存用户信息
      localStorage.setItem("userID", response.data.user.id);
      localStorage.setItem("userInfoname", response.data.user.username);
      localStorage.setItem("userToken", response.data.user.token);
      // 更新登录状态
      checkLoginStatus();
      // 重新加载数据
      await fetchMusicData();
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error("用户名或密码错误");
    } else {
      ElMessage.error("登录失败，请检查网络连接");
    }
  }
};

// 退出登录
const handleLogout = () => {
  ifLogin.value = false;
  ElMessage.success("退出登录成功");
  // 清除本地存储
  localStorage.removeItem("userID");
  localStorage.removeItem("userToken");
  localStorage.removeItem("userInfoname");
  // 重置用户信息
  userInfo.userID = "";
  userInfo.userInfoname = "";
  userInfo.userToken = "";
  // 重置表单
  form.username = "";
  form.password = "";
  // 重置歌曲收藏状态
  musicList.value.forEach((song) => (song.isLiked = false));
  searchResults.value = [...musicList.value];
};

// 注册跳转
const goToRegister = () => {
  router.push("/register");
};

// 跳转到用户中心
const goUserInfo = () => {
  router.push("/userinfo");
};

// 获取音乐数据
const fetchMusicData = async () => {
  try {
    // 获取所有歌曲
    const songsResponse = await axios.get("http://localhost:3001/api/songs");
    const allSongs = songsResponse.data;

    if (ifLogin.value) {
      try {
        const token = localStorage.getItem("userToken");
        // 获取用户收藏
        const userSongsResponse = await axios.get(
          "http://localhost:3001/api/usersongs",
          { headers: { Authorization: `Bearer ${token}` } }
        );
        const userSongIds = userSongsResponse.data.map((song) => song.id);
        // 标记收藏状态
        allSongs.forEach((song) => {
          song.isLiked = userSongIds.includes(song.id);
        });
      } catch (error) {
        console.error("获取收藏列表失败:", error);
      }
    } else {
      allSongs.forEach((song) => (song.isLiked = false));
    }

    musicList.value = allSongs;
    searchResults.value = allSongs;
    isLoading.value = false;
  } catch (error) {
    console.error("数据获取失败:", error);
    errorMessage.value = "数据加载失败，请稍后重试";
    isLoading.value = false;
  }
};

// 处理搜索
const performSearch = () => {
  if (!searchKeyword.value.trim()) {
    searchResults.value = musicList.value;
    return;
  }

  const keyword = searchKeyword.value.trim().toLowerCase();
  searchResults.value = musicList.value.filter(
    (music) =>
      music.songtitle?.toLowerCase().includes(keyword) ||
      music.songauthor?.toLowerCase().includes(keyword)
  );
  currentPage.value = 1; // 重置分页
};

const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }

  isSearching.value = true;
  performSearch();
  isSearching.value = false;
};

const handleEnterSearch = () => {
  handleSearch();
};

// 切换收藏状态
const toggleLike = async (music) => {
  if (!ifLogin.value) {
    ElMessage.warning("请先登录");
    dialogFormVisible.value = true;
    return;
  }

  const token = localStorage.getItem("userToken");
  try {
    if (music.isLiked) {
      // 取消收藏
      await axios.delete(`http://localhost:3001/api/usersongs/${music.id}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      ElMessage.success("已取消收藏");
    } else {
      // 收藏
      await axios.post(
        "http://localhost:3001/api/usersongs",
        {
          songId: music.id,
          songTitle: music.songtitle,
          songAuthor: music.songauthor,
          songPath: music.songpath,
        },
        { headers: { Authorization: `Bearer ${token}` } }
      );
      ElMessage.success("收藏成功");
    }
    // 更新本地状态
    music.isLiked = !music.isLiked;
    // 更新搜索结果中的状态
    searchResults.value = [...musicList.value];
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  }
};

// 跳转音乐详情
const goMusicDetail = (music) => {
  router.push({
    name: "MusicDetail",
    params: {
      id: music.id,
    },
  });
};

// 计算属性
const filteredMusicList = computed(() => {
  return searchResults.value;
});

const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return searchResults.value.slice(start, end);
});

// 监听路由参数变化，自动触发搜索
watch(
  () => route.query.keyword,
  (newKeyword) => {
    if (typeof newKeyword === "string") {
      searchKeyword.value = newKeyword;
      handleSearch();
    }
  },
  { immediate: true }
);

// 生命周期钩子
onMounted(async () => {
  checkLoginStatus();
  await fetchMusicData();

  // 检查路由参数中的关键词
  const keyword = route.query.keyword;
  if (typeof keyword === "string") {
    searchKeyword.value = keyword;
    handleSearch();
  }
});

// 分页处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
</script>

<style lang="scss" scoped>
$primary-color: #ff4d4f;
$dark-bg: #1a1a1a;
$text-primary: #ffffff;

.discover-container {
  height: 140vh;
  background: linear-gradient(45deg, #0a0a0a 0%, #1a1a1a 100%);
}

/* 顶部导航栏样式 */
.discover-header {
  height: 140px;
  padding: 0 20px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(5px);
  border-bottom: 1px solid #333;

  .header-content {
    max-width: 1200px;
    margin: 0 auto;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .back-home {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    color: $text-primary;
    transition: color 0.3s;

    &:hover {
      color: $primary-color;
    }

    .el-icon {
      font-size: 1.6rem;
    }

    span {
      font-size: 1.2rem;
    }
  }

  .search-container {
    flex: 1;
    max-width: 600px;
    margin: 0 30px;
    display: flex;
    gap: 10px;
    height: 40px;

    .search-input {
      :deep(.el-input__wrapper) {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 20px;
        box-shadow: none;
        padding: 0 20px;

        .el-icon {
          color: #888;
          font-size: 18px;
        }

        input {
          color: $text-primary;

          &::placeholder {
            color: #666;
          }
        }
      }
    }

    .search-btn {
      border-radius: 20px;
      padding: 0 30px;
      font-weight: 500;
      letter-spacing: 1px;
      border: none;
      width: 68px;
      height: 40px;
      background-color: #ff4d4f;
    }

    .search-btn:hover {
      transition: background-color 0.3s;
      background-color: #ff1919;
    }
  }

  .user-info {
    .login-register {
      display: flex;
      gap: 20px;
      color: $text-primary;
      span {
        cursor: pointer;
        padding: 8px 16px;
        border-radius: 4px;
        transition: all 0.3s;

        &:hover {
          background-color: rgba(255, 255, 255, 0.1);
          color: $primary-color;
        }
      }
    }

    .user-info-content {
      font-size: 20px;
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 8px 16px;
      cursor: pointer;
      transition: background 0.3s;

      &:hover {
        background: rgba(255, 255, 255, 0.05);
      }

      .user-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        border: 1px solid rgba(255, 255, 255, 0.1);
      }

      .user-name {
        color: $text-primary;
        font-size: 20px;
      }
    }
  }
}

/* 音乐列表样式 */
.music-list-container {
  padding: 30px 20px;
  max-width: 1400px;
  width: 1400px;
  margin: 0 auto;
}

.music-table {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  overflow: hidden;
}

.search-results {
  padding: 20px 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);

  .result-title {
    color: $text-primary;
    font-size: 18px;
    margin-bottom: 5px;
  }

  .result-count {
    color: #888;
    font-size: 14px;
  }
}

.table-header {
  display: flex;
  align-items: center;
  padding: 16px 24px;
  background: rgba(255, 255, 255, 0.08);
  color: #888;
  font-size: 14px;

  .title {
    flex: 2;
  }
  .artist {
    flex: 1;
  }
  .action {
    width: 80px;
    text-align: center;
  }
}

.table-body {
  .table-row {
    display: flex;
    align-items: center;
    padding: 16px 24px;
    transition: background 0.3s;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);

    &:hover {
      background: rgba(255, 255, 255, 0.03);
    }

    .title {
      flex: 2;
      color: $text-primary;
      font-size: 14px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .artist {
      flex: 1;
      color: #888;
      font-size: 14px;
    }

    .like-icon {
      width: 80px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s;
      font-size: 18px;

      &:hover {
        transform: scale(1.2);
      }
    }
  }
}

/* 分页样式 */
.pagination-container {
  padding: 20px 0;
  display: flex;
  justify-content: center;

  :deep(.el-pagination) {
    --el-pagination-bg-color: rgba(255, 255, 255, 0.05);
    --el-pagination-button-disabled-bg-color: transparent;
    --el-pagination-hover-color: $primary-color;
  }

  :deep(.el-pager) {
    li {
      background: rgba(255, 255, 255, 0.05);
      color: #666;
      border-radius: 8px;
      margin: 0 4px;
      min-width: 36px;
      height: 36px;

      &:not(.is-disabled):hover {
        background: rgba(255, 255, 255, 0.08);
        color: $primary-color;
      }

      &.is-active {
        background: $primary-color;
        color: white;
      }
    }
  }

  :deep(.btn-prev),
  :deep(.btn-next) {
    background: transparent;
    color: #666;
    border-radius: 8px;
    padding: 0 12px;

    &:not(.is-disabled):hover {
      color: $primary-color;
    }
  }
}

/* 加载和错误状态样式 */
.loading-container,
.error-container {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #888;

  .el-icon {
    margin-bottom: 10px;
  }
}

.error-container {
  color: $primary-color;
}

/* 登录对话框样式 */
:deep(.el-dialog) {
  background: #1e1e1e;
  border-radius: 12px;
  border: 1px solid #404040;

  .el-dialog__title {
    color: white;
  }

  .el-form-item__label {
    color: white !important;
  }

  .el-input__wrapper {
    background: #fff;
    margin-right: 30px;
  }
}
</style>
